package com.zhangyj.applets.data;

import java.util.Stack;

import javax.swing.tree.DefaultMutableTreeNode;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.zhangyj.applets.data.DBService.MenuNode;

public class TreeRead extends DefaultHandler {
	DefaultMutableTreeNode root = new DefaultMutableTreeNode(new MenuNode(-1, "系统功能"));
	Stack<DefaultMutableTreeNode> stack = new Stack<DefaultMutableTreeNode>();

	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException {
		if ("n".equals(qName) == false) {
			return;
		}
		String sid = attrs.getValue("s");
		if (sid== null || sid.length() ==0) {
			sid = "0";
		}
		MenuNode node = new MenuNode(Integer.parseInt(sid), attrs.getValue("d"));
		DefaultMutableTreeNode item = new DefaultMutableTreeNode(node);
		stack.push(item);
	}

	@Override
	public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
		if ("n".equals(qName) == false) {
			return;
		}
		DefaultMutableTreeNode item = stack.pop();
		if (stack.size() > 0) {
			stack.get(stack.size() - 1).add(item);
		} else {
			root.add(item);
		}
	}

	public DefaultMutableTreeNode getResult() {
		return root;
	}
}
